import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpHeaders,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd/message';
import { stringify } from '@angular/compiler/src/util';
import { JsonPipe } from '@angular/common';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private message: NzMessageService) {}

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    const idToken = sessionStorage.getItem('token'); //"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDUzODM0MzksInVzZXJfbmFtZSI6IlJPT1QiLCJhdXRob3JpdGllcyI6WyJTWVNBRE1JTiJdLCJqdGkiOiI2NDdlZDNiZC03YjQ3LTRlMjItOGQxMC1kZWYyMGNhNjFlNTMiLCJjbGllbnRfaWQiOiJzcGFycm93Iiwic2NvcGUiOlsiYW55Il19.dWkWOYYSGND07PRd0YBe0y5VG7Lsgaj0grMblmg8aVN1aQS-aDwN53n_OuKinA27JZ5ReZ5j_KpvG6zLA1zI4upb4xkGKd6pRaYu6Q7ywmAuPhnLdZYViMg7IjpMuQmrHkB7Z8BYWykptyP1D1uCwKS3mNGwCAlKpcUrierFmgttorvS86a5eUBK4m519IEo5w074s3Wa5r8Kxcl3phmTcIHSd_0vtFGKxf10QhDz6AlZgWWDYVwepazjxdtCc9qt7KaE21KktaDa40E_ZjVtimUxlbngtjyWd0hvk-Ht-BGgMCu_2g_ufruDW6QVGP6LMbxUaZqZPNt2wS91QlxUw";
    // const headers1 = new HttpHeaders();
    // headers1.set('Content-Type', 'application/json; charset=utf-8');
    if (idToken != undefined) {
      // headers1.set('Authorization', 'Bearer ' + idToken);
      const authReq = request.clone({
        setHeaders: { Authorization: 'Bearer ' + idToken },
      });
      return next.handle(authReq).pipe(
        catchError((error) => {
          console.log('error is intercept')
          console.error(error);
          if(error.status===403)
            this.message.error("无权限！" + error.error.error)
          else
            this.message.error("系统错误" + error.status + error.error.error)

          return throwError(error.message);
        })
      );
    } else {
      return next.handle(request);
    }
  }
}
